package com.algo.rpc.common;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import org.apache.log4j.Logger;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 序列化工具类
 */
public class HessionSerializeUtil {

    private static final Logger logger = Logger.getLogger(HessionSerializeUtil.class);

    /**
     * 序列化
     *
     * @param object
     * @return
     */
    public static byte[] serialize(Object object) {
        byte[] result = null;
        Hessian2Output output = null;
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            output = new Hessian2Output(bos);
            output.writeObject(object);
            output.flush();
            result = bos.toByteArray();
        } catch (IOException e) {
            logger.error("serialize error ", e);
        } finally {
            try {
                output.close();
            } catch (IOException e) {
            }
            try {
                bos.close();
            } catch (IOException e) {
            }
        }
        return result;
    }

    /**
     * 反序列化
     *
     * @param bytes
     * @return
     */
    public static Object deserialize(byte[] bytes) {
        Object result = null;
        ByteArrayInputStream is = null;
        Hessian2Input input = null;
        try {
            is = new ByteArrayInputStream(bytes);
            input = new Hessian2Input(is);
            result = input.readObject();
        } catch (Exception e) {
            logger.error("deserialize error ", e);
        } finally {
            try {
                is.close();
            } catch (IOException e) {
            }
            try {
                input.close();
            } catch (IOException e) {
            }
        }
        return result;
    }

}
